package com.mfnote.view.hand;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.mfnote.model.HandInsertEntity;
import com.mfnote.util.image.ImageManager;
import com.mfnote.view.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.widget.Toast;

public class HandWritingView extends SurfaceView implements Callback, Runnable {
	private SurfaceHolder surHolder = null;
	private boolean isRun = false;
	private Canvas canvas = null;
	private Canvas cachedcanvas = null;

	private Thread thread = null;

	private Paint paint = null;

	private Path path = null;
	private Bitmap cachebBitmap = null;
	private float cur_x, cur_y;

	private long startTime = 0;
	private long endTime = 0;

	private boolean isCanSave = false;

	private Handler handler = null;
	
	private File destDir = null;
	
	//是否是连笔
	private boolean isCursive = false;
	
	private Context context = null;
	public HandWritingView(Context context, Handler handler) {
		super(context);
        this.context = context;
		this.handler = handler;

		this.surHolder = this.getHolder();
		this.surHolder.addCallback(this);

		setZOrderOnTop(true);
		surHolder.setFormat(PixelFormat.TRANSLUCENT);

		paint = new Paint();
		paint.setStrokeWidth(20);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeJoin(Paint.Join.ROUND);
		paint.setStrokeCap(Paint.Cap.ROUND);
		paint.setAntiAlias(true);
		paint.setDither(true); 
		paint.setColor(0Xff2E7EC1);

		path = new Path();
		cachebBitmap = Bitmap.createBitmap(480, 450, Config.ARGB_8888);
		cachedcanvas = new Canvas(cachebBitmap);
	}

	public HandWritingView(Context context, AttributeSet attrs) {
		super(context, attrs);

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread = new Thread(this);
		thread.start();
		isRun = true;
	}

	@Override
	public void run() {
		while (isRun) {
			try {
				if (surHolder != null) {
					canvas = surHolder.lockCanvas();
					endTime = System.currentTimeMillis();
					// 如果两次画的时间间距超过1500ms则将图片缩小保存
					if (isCanSave) {
						if(isCursive){
							//是连笔
						}else{
							//不是连笔
							if (startTime != 0 && endTime != 0) {
								if (endTime - startTime > 200) {
									startTime = endTime;
									// 清空画布
									Log.d("save", "需要保存图片");
									save();
									isCanSave = false;
									// 清空canvas上的所有的数据
									cachebBitmap = Bitmap.createBitmap(480, 450,
											Config.ARGB_8888);
									cachedcanvas.setBitmap(cachebBitmap);
									cachedcanvas.drawColor(Color.WHITE);

								}
							}
						}
					}
					draw();

				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (canvas != null) {
					surHolder.unlockCanvasAndPost(canvas);
				}
			}

		}
	}

	private void save() {
		try {
			//保存图片到/mnt/sdcard/MFNote/hand
			Bitmap bit = ImageManager.zoomBitmap(getTandBitmap(cachebBitmap), 60, 80);
			//Bitmap bit = getTandBitmap(resizeBitmap(cachebBitmap));
			
			Log.d("bitmap_", "图片宽高"+bit.getWidth()+"---,---"+bit.getHeight());
			
			String bitmapName = createBitmapName();
			createFile();
			FileOutputStream fos = new FileOutputStream(new File("/mnt/sdcard/MFNote/hand/"+bitmapName));
			bit.compress(CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
			// 通知主界面editText中的数据发生改变
			Message msg = new Message();
			msg.what = 10;
			msg.obj = new HandInsertEntity(bit, bitmapName);
			handler.sendMessage(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void draw() {
		if (canvas != null) {
			canvas.drawBitmap(cachebBitmap, 0, 0, null);
			canvas.drawPath(path, paint);
		}

	}
	
	private  Bitmap resizeBitmap(Bitmap bitmap) {
		Bitmap bit = bitmap;
		int width = bit.getWidth();
		int height = bit.getHeight();

		int bitW = 60;
		int bitH = 80;

		float scaleW = (float) bitW / width;
		float scaleH = (float) bitH / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleW, scaleH);

		Bitmap bit_return = Bitmap.createBitmap(bit, 0, 0, width, height,
				matrix, true);

		return bit_return;
	}


	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		isRun = false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			isCursive  = true;
			cur_x = x;
			cur_y = y;
			path.moveTo(cur_x, cur_y);
			break;
		}

		case MotionEvent.ACTION_MOVE: {
			path.quadTo(cur_x, cur_y, x, y);
			cur_x = x;
			cur_y = y;
			break;
		}
		case MotionEvent.ACTION_UP: {
			isCursive  = false;
			startTime = System.currentTimeMillis();
			isCanSave = true;
			Log.d("down", "------down-----");
			cachedcanvas.drawPath(path, paint);
			path.reset();
			break;
		}
		}

		return true;
	}
	
	/**创建图片的名称**/
	private String createBitmapName(){
		Date date = new Date(System.currentTimeMillis());  //系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String fileName = dateFormat.format(date)+".png";
		return fileName;
	}
	
	/**获得SD开的路径**/
	private String getSDCardPath() {
		String sdcardDir = null;
		boolean sdcardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) { // 判断是否有SD卡
			sdcardDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
		} else {
			Toast.makeText(context, "没有找到SD卡", Toast.LENGTH_SHORT).show();
		}

		return sdcardDir;
	}
	
	/**创建手写文件的保存位置**/
	private void createFile(){
		destDir = new File(getSDCardPath() + "/MFNote/hand");
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
	}
	

	/**将图片的黑色背景换成白色**/
	private  Bitmap getTandBitmap(Bitmap bitmap) {
		Bitmap bit = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight());

		int argb = 0;
		for (int x = 0; x < bit.getWidth(); x++) {
			for (int y = 0; y < bit.getHeight(); y++) {
				argb = bit.getPixel(x, y);
				if (argb == 0) {
					bit.setPixel(x, y, 0xFFFFFFFF);
				}
			}
		}
		return bit;
	}

}
